#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
HTML 报告生成器
为 Git 代码统计生成精美的 HTML 报告
"""

import datetime
from typing import Dict


class HTMLReportGenerator:
    """HTML 报告生成器"""
    
    def __init__(self, repo_path: str, user_name: str, user_email: str, branch: str):
        """
        初始化报告生成器
        
        Args:
            repo_path: 仓库路径
            user_name: Git 用户名
            user_email: Git 邮箱
            branch: 分支名
        """
        self.repo_path = repo_path
        self.user_name = user_name
        self.user_email = user_email
        self.branch = branch
        self.timestamp = datetime.datetime.now()
    
    def generate(self, stats: Dict, file_stats: Dict, output_path: str = None, per_user_stats: Dict = None, user_list: list = None) -> str:
        """
        生成 HTML 报告
        
        Args:
            stats: 统计数据
            file_stats: 文件统计数据
            output_path: 输出路径（可选）
            per_user_stats: 分账户统计数据（可选）
            user_list: 用户列表（可选）
        
        Returns:
            HTML 内容
        """
        if output_path is None:
            output_path = f"git_report_{self.timestamp.strftime('%Y%m%d_%H%M%S')}.html"
        
        html_content = self._generate_html(stats, file_stats, per_user_stats, user_list)
        
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(html_content)
        
        return output_path
    
    def _generate_html(self, stats: Dict, file_stats: Dict, per_user_stats: Dict = None, user_list: list = None) -> str:
        """生成 HTML 内容"""
        is_detailed = per_user_stats is not None and user_list is not None and len(user_list) > 1
        
        # 计算总计
        frontend = stats['frontend']
        backend = stats['backend']
        other = stats['other']
        
        total_added = frontend['added'] + backend['added'] + other['added']
        total_deleted = frontend['deleted'] + backend['deleted'] + other['deleted']
        total_net = frontend['total'] + backend['total'] + other['total']
        total_current = frontend.get('current', 0) + backend.get('current', 0) + other.get('current', 0)
        
        # 检查是否有当前代码量数据
        has_current_stats = total_current > 0
        
        # 计算百分比
        total_code = total_added + total_deleted
        frontend_percent = ((frontend['added'] + frontend['deleted']) / total_code * 100) if total_code > 0 else 0
        backend_percent = ((backend['added'] + backend['deleted']) / total_code * 100) if total_code > 0 else 0
        other_percent = ((other['added'] + other['deleted']) / total_code * 100) if total_code > 0 else 0
        
        # 计算工作效率比
        work_ratio = (total_added / total_current * 100) if total_current > 0 else 0
        
        # 准备所有文件数据（不再限制为Top 20）
        sorted_files = sorted(
            file_stats.items(),
            key=lambda x: x[1]['added'] - x[1]['deleted'],
            reverse=True
        )
        
        html = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Git 代码统计报告 - {self.user_name}</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <style>
        * {{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }}
        
        body {{
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #333;
            padding: 20px;
            min-height: 100vh;
        }}
        
        .container {{
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            overflow: hidden;
        }}
        
        .header {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 40px;
            text-align: center;
        }}
        
        .header h1 {{
            font-size: 2.5em;
            margin-bottom: 10px;
            font-weight: 700;
        }}
        
        .header .subtitle {{
            font-size: 1.2em;
            opacity: 0.9;
        }}
        
        .meta-info {{
            background: #f8f9fa;
            padding: 30px 40px;
            border-bottom: 3px solid #e9ecef;
        }}
        
        .meta-grid {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
        }}
        
        .meta-item {{
            display: flex;
            align-items: center;
            padding: 15px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }}
        
        .meta-item .icon {{
            font-size: 2em;
            margin-right: 15px;
        }}
        
        .meta-item .label {{
            font-size: 0.9em;
            color: #6c757d;
            display: block;
        }}
        
        .meta-item .value {{
            font-size: 1.1em;
            font-weight: 600;
            color: #333;
        }}
        
        .content {{
            padding: 40px;
        }}
        
        /* 选项卡样式 */
        .tabs {{
            display: flex;
            border-bottom: 2px solid #e9ecef;
            margin-bottom: 30px;
            gap: 10px;
        }}
        
        .tab-button {{
            padding: 15px 30px;
            background: transparent;
            border: none;
            border-bottom: 3px solid transparent;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            color: #6c757d;
            transition: all 0.3s;
        }}
        
        .tab-button:hover {{
            color: #667eea;
            background: #f8f9fa;
        }}
        
        .tab-button.active {{
            color: #667eea;
            border-bottom-color: #667eea;
            background: #f8f9fa;
        }}
        
        .tab-content {{
            display: none;
        }}
        
        .tab-content.active {{
            display: block;
            animation: fadeIn 0.3s;
        }}
        
        @keyframes fadeIn {{
            from {{ opacity: 0; transform: translateY(10px); }}
            to {{ opacity: 1; transform: translateY(0); }}
        }}
        
        .section {{
            margin-bottom: 40px;
        }}
        
        .section-title {{
            font-size: 1.8em;
            margin-bottom: 20px;
            color: #667eea;
            border-left: 5px solid #667eea;
            padding-left: 15px;
        }}
        
        .stats-grid {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }}
        
        .stat-card {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
            transition: transform 0.3s ease;
        }}
        
        .stat-card:hover {{
            transform: translateY(-5px);
        }}
        
        .stat-card.frontend {{
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }}
        
        .stat-card.backend {{
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }}
        
        .stat-card.other {{
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }}
        
        .stat-card.total {{
            background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
        }}
        
        .stat-card h3 {{
            font-size: 1.5em;
            margin-bottom: 20px;
            opacity: 0.95;
        }}
        
        .stat-item {{
            display: flex;
            justify-content: space-between;
            margin-bottom: 12px;
            padding: 10px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 8px;
        }}
        
        .stat-item .label {{
            font-size: 0.95em;
        }}
        
        .stat-item .value {{
            font-weight: 700;
            font-size: 1.1em;
        }}
        
        .chart-container {{
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            margin-bottom: 30px;
        }}
        
        .chart-container h3 {{
            text-align: center;
            color: #667eea;
            margin-bottom: 20px;
            font-size: 1.3em;
        }}
        
        .chart-wrapper {{
            position: relative;
            height: 300px;
            margin-bottom: 20px;
        }}
        
        .file-list {{
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }}
        
        .file-item {{
            padding: 20px 25px;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            align-items: center;
            transition: background 0.2s ease;
        }}
        
        .file-item:hover {{
            background: #f8f9fa;
        }}
        
        .file-item:last-child {{
            border-bottom: none;
        }}
        
        .file-rank {{
            font-size: 1.5em;
            font-weight: 700;
            color: #667eea;
            width: 50px;
            text-align: center;
        }}
        
        .file-info {{
            flex: 1;
            margin-left: 20px;
        }}
        
        .file-path {{
            font-size: 1em;
            color: #333;
            margin-bottom: 8px;
            font-family: 'Courier New', monospace;
            word-break: break-all;
        }}
        
        .file-stats {{
            display: flex;
            gap: 20px;
            font-size: 0.9em;
        }}
        
        .stat-badge {{
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
        }}
        
        .stat-badge.added {{
            background: #d4edda;
            color: #155724;
        }}
        
        .stat-badge.deleted {{
            background: #f8d7da;
            color: #721c24;
        }}
        
        .stat-badge.net {{
            background: #d1ecf1;
            color: #0c5460;
        }}
        
        .footer {{
            background: #f8f9fa;
            padding: 30px;
            text-align: center;
            color: #6c757d;
            font-size: 0.9em;
        }}
        
        /* 完整文件列表样式 */
        .full-file-list {{
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            padding: 30px;
        }}
        
        .full-file-list table.dataTable {{
            width: 100% !important;
            border-collapse: collapse;
            margin-top: 20px;
        }}
        
        .full-file-list table.dataTable thead th {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 10px;
            font-weight: 600;
            text-align: left;
            border: none;
        }}
        
        .full-file-list table.dataTable thead th:first-child {{
            border-radius: 10px 0 0 0;
        }}
        
        .full-file-list table.dataTable thead th:last-child {{
            border-radius: 0 10px 0 0;
        }}
        
        .full-file-list table.dataTable tbody td {{
            padding: 12px 10px;
            border-bottom: 1px solid #e9ecef;
        }}
        
        .full-file-list table.dataTable tbody tr:hover {{
            background: #f8f9fa;
        }}
        
        .full-file-list table.dataTable tbody tr:last-child td {{
            border-bottom: none;
        }}
        
        .file-path-cell {{
            font-family: 'Courier New', monospace;
            font-size: 0.9em;
            color: #333;
            word-break: break-all;
        }}
        
        .number-cell {{
            text-align: right !important;
            font-weight: 600;
            font-family: 'Consolas', monospace;
        }}
        
        .positive-number {{
            color: #28a745;
        }}
        
        .negative-number {{
            color: #dc3545;
        }}
        
        .rank-cell {{
            text-align: center !important;
            font-weight: 700;
            font-size: 1.1em;
            color: #667eea;
        }}
        
        .rank-1 {{ color: #FFD700; }}
        .rank-2 {{ color: #C0C0C0; }}
        .rank-3 {{ color: #CD7F32; }}
        
        .dataTables_wrapper .dataTables_length,
        .dataTables_wrapper .dataTables_filter,
        .dataTables_wrapper .dataTables_info,
        .dataTables_wrapper .dataTables_paginate {{
            margin-top: 15px;
            margin-bottom: 15px;
        }}
        
        .dataTables_wrapper .dataTables_filter input {{
            border: 2px solid #e9ecef;
            border-radius: 8px;
            padding: 8px 15px;
            margin-left: 10px;
        }}
        
        .dataTables_wrapper .dataTables_length select {{
            border: 2px solid #e9ecef;
            border-radius: 8px;
            padding: 5px 10px;
            margin: 0 10px;
        }}
        
        .dataTables_wrapper .dataTables_paginate .paginate_button {{
            border-radius: 5px;
            padding: 5px 12px;
            margin: 0 2px;
        }}
        
        .dataTables_wrapper .dataTables_paginate .paginate_button.current {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
            color: white !important;
            border: none !important;
        }}
        
        .extension-badge {{
            display: inline-block;
            padding: 3px 10px;
            border-radius: 12px;
            font-size: 0.85em;
            font-weight: 600;
            background: #e9ecef;
            color: #495057;
        }}
        
        .extension-badge.frontend {{
            background: #ffc1e3;
            color: #c2185b;
        }}
        
        .extension-badge.backend {{
            background: #b3e5fc;
            color: #0277bd;
        }}
        
        .summary-cards {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }}
        
        .summary-card {{
            background: white;
            padding: 25px;
            border-radius: 12px;
            box-shadow: 0 3px 15px rgba(0, 0, 0, 0.08);
            text-align: center;
            border-top: 4px solid #667eea;
        }}
        
        .summary-card .number {{
            font-size: 2.5em;
            font-weight: 700;
            color: #667eea;
            margin: 10px 0;
        }}
        
        .summary-card .label {{
            color: #6c757d;
            font-size: 0.95em;
        }}
        
        @media print {{
            body {{
                background: white;
                padding: 0;
            }}
            
            .stat-card:hover {{
                transform: none;
            }}
        }}
        
        @media (max-width: 768px) {{
            .header h1 {{
                font-size: 1.8em;
            }}
            
            .stats-grid {{
                grid-template-columns: 1fr;
            }}
            
            .meta-grid {{
                grid-template-columns: 1fr;
            }}
        }}
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <h1>📊 Git 代码统计报告</h1>
            <div class="subtitle">Code Statistics Report</div>
        </div>
        
        <!-- Meta Information -->
        <div class="meta-info">
            <div style="background: #fff3cd; border-left: 4px solid #ffc107; padding: 15px; margin-bottom: 20px; border-radius: 8px;">
                <strong style="color: #856404;">📊 统计说明：</strong>
                <span style="color: #856404;">本报告仅统计下方指定用户的 Git 提交记录，基于 Git diff 分析每次提交的代码变更。不包括项目原始代码，只统计该用户新增/删除的代码行数（已排除注释和空行）。</span>
            </div>
            <div class="meta-grid">
                <div class="meta-item">
                    <div class="icon">👤</div>
                    <div>
                        <span class="label">报告生成者</span>
                        <div class="value" style="color: #667eea; font-weight: bold;">{self.user_name if self.user_name else '未配置'}</div>
                    </div>
                </div>
                {'<div class="meta-item"><div class="icon">📧</div><div><span class="label">生成者邮箱</span><div class="value">' + self.user_email + '</div></div></div>' if self.user_email else ''}
                <div class="meta-item">
                    <div class="icon">📁</div>
                    <div>
                        <span class="label">仓库路径</span>
                        <div class="value" style="font-size: 0.9em; word-break: break-all;">{self.repo_path}</div>
                    </div>
                </div>
                <div class="meta-item">
                    <div class="icon">🌿</div>
                    <div>
                        <span class="label">分支</span>
                        <div class="value">{self.branch}</div>
                    </div>
                </div>
                <div class="meta-item">
                    <div class="icon">📅</div>
                    <div>
                        <span class="label">生成时间</span>
                        <div class="value">{self.timestamp.strftime('%Y-%m-%d %H:%M:%S')}</div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Main Content -->
        <div class="content">
        """
        
        # 如果是分账户模式，在这之前插入选项卡
        if is_detailed:
            html += '<div class="tabs">'
            html += '<button class="tab-button active" onclick="switchTab(\'summary\')">📊 汇总统计</button>'
            for idx, user in enumerate(user_list, 1):
                html += f'<button class="tab-button" onclick="switchTab(\'user{idx}\')">👤 {user}</button>'
            html += '<button class="tab-button" onclick="switchTab(\'comparison\')">📈 账户对比</button>'
            html += '</div>'
            html += '<div id="summary" class="tab-content active">'
        
        # 构建汇总卡片 HTML
        summary_cards_html = f"""
            <!-- Summary Cards -->
            <div class="section">
                <h2 class="section-title">📈 整体概览</h2>
                <p style="text-align: center; color: #666; margin-bottom: 20px; font-size: 14px;">
                    {'📊 累计工作量：统计所有历史提交的代码变更 | 📝 当前代码量：统计当前代码库中属于你的有效代码' if has_current_stats else '📊 累计工作量：统计所有历史提交的代码变更'}
                </p>
                <div class="summary-cards">
                    <div class="summary-card">
                        <div class="label">累计新增行数</div>
                        <div class="number">{total_added:,}</div>
                    </div>
                    <div class="summary-card">
                        <div class="label">累计删除行数</div>
                        <div class="number">{total_deleted:,}</div>
                    </div>
                    <div class="summary-card">
                        <div class="label">净增行数</div>
                        <div class="number">{total_net:,}</div>
                    </div>
                    {'<div class="summary-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);"><div class="label">当前代码量</div><div class="number">' + f'{total_current:,}</div></div>' if has_current_stats else ''}
                    <div class="summary-card">
                        <div class="label">修改文件数</div>
                        <div class="number">{len(file_stats)}</div>
                    </div>
                    {'<div class="summary-card" style="background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);"><div class="label">工作效率比</div><div class="number" style="font-size: 32px;">' + f'{work_ratio:.0f}%</div><div style="font-size: 12px; margin-top: 5px;">累计÷当前</div></div>' if has_current_stats else ''}
                </div>
            </div>"""
        
        html += summary_cards_html
        
        # 详细统计卡片
        detail_stats_html = f"""
            
            <!-- Statistics Cards -->
            <div class="section">
                <h2 class="section-title">💻 详细统计</h2>
                <div class="stats-grid">
                    <div class="stat-card frontend">
                        <h3>🎨 前端代码</h3>
                        <div class="stat-item">
                            <span class="label">新增行数</span>
                            <span class="value">+{frontend['added']:,}</span>
                        </div>
                        <div class="stat-item">
                            <span class="label">删除行数</span>
                            <span class="value">-{frontend['deleted']:,}</span>
                        </div>
                        <div class="stat-item">
                            <span class="label">净增行数</span>
                            <span class="value">{frontend['total']:,}</span>
                        </div>
                        {'<div class="stat-item"><span class="label">当前拥有</span><span class="value" style="color: #f093fb;">' + f"{frontend.get('current', 0):,}</span></div>" if has_current_stats else ''}
                        <div class="stat-item">
                            <span class="label">占比</span>
                            <span class="value">{frontend_percent:.1f}%</span>
                        </div>
                    </div>
                    
                    <div class="stat-card backend">
                        <h3>⚙️ 后端代码</h3>
                        <div class="stat-item">
                            <span class="label">新增行数</span>
                            <span class="value">+{backend['added']:,}</span>
                        </div>
                        <div class="stat-item">
                            <span class="label">删除行数</span>
                            <span class="value">-{backend['deleted']:,}</span>
                        </div>
                        <div class="stat-item">
                            <span class="label">净增行数</span>
                            <span class="value">{backend['total']:,}</span>
                        </div>
                        {'<div class="stat-item"><span class="label">当前拥有</span><span class="value" style="color: #f093fb;">' + f"{backend.get('current', 0):,}</span></div>" if has_current_stats else ''}
                        <div class="stat-item">
                            <span class="label">占比</span>
                            <span class="value">{backend_percent:.1f}%</span>
                        </div>
                    </div>
                    
                    <div class="stat-card other">
                        <h3>📄 其他文件</h3>
                        <div class="stat-item">
                            <span class="label">新增行数</span>
                            <span class="value">+{other['added']:,}</span>
                        </div>
                        <div class="stat-item">
                            <span class="label">删除行数</span>
                            <span class="value">-{other['deleted']:,}</span>
                        </div>
                        <div class="stat-item">
                            <span class="label">净增行数</span>
                            <span class="value">{other['total']:,}</span>
                        </div>
                        {'<div class="stat-item"><span class="label">当前拥有</span><span class="value" style="color: #f093fb;">' + f"{other.get('current', 0):,}</span></div>" if has_current_stats else ''}
                        <div class="stat-item">
                            <span class="label">占比</span>
                            <span class="value">{other_percent:.1f}%</span>
                        </div>
                    </div>
                    
                    <div class="stat-card total">
                        <h3>📊 总计</h3>
                        <div class="stat-item">
                            <span class="label">新增行数</span>
                            <span class="value">+{total_added:,}</span>
                        </div>
                        <div class="stat-item">
                            <span class="label">删除行数</span>
                            <span class="value">-{total_deleted:,}</span>
                        </div>
                        <div class="stat-item">
                            <span class="label">净增行数</span>
                            <span class="value">{total_net:,}</span>
                        </div>
                        {'<div class="stat-item"><span class="label">当前拥有</span><span class="value" style="color: #f093fb; font-weight: bold;">' + f'{total_current:,}</span></div>' if has_current_stats else ''}
                        <div class="stat-item">
                            <span class="label">总变更</span>
                            <span class="value">{total_code:,}</span>
                        </div>
                    </div>
                </div>
            </div>"""
        
        html += detail_stats_html
        
        # 图表和文件列表（汇总统计不显示文件列表）
        charts_html = f"""
            
            <!-- Charts -->
            <div class="section">
                <h2 class="section-title">📊 数据可视化</h2>
                
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 20px;">
                    <div class="chart-container">
                        <h3>代码类型分布</h3>
                        <div class="chart-wrapper">
                            <canvas id="typeChart"></canvas>
                        </div>
                    </div>
                    
                    <div class="chart-container">
                        <h3>新增 vs 删除</h3>
                        <div class="chart-wrapper">
                            <canvas id="addDeleteChart"></canvas>
                        </div>
                    </div>
                </div>
                
                <div class="chart-container">
                    <h3>前端 vs 后端对比</h3>
                    <div class="chart-wrapper">
                        <canvas id="comparisonChart"></canvas>
                    </div>
                </div>
            </div>
        """
        
        html += charts_html
        
        # 关闭汇总选项卡，添加其他选项卡
        if is_detailed:
            html += '</div>'  # 关闭summary选项卡
            
            # 为每个账户添加选项卡
            for idx, user in enumerate(user_list, 1):
                if user not in per_user_stats:
                    continue
                html += f'<div id="user{idx}" class="tab-content">'
                html += self._generate_user_tab_content(user, per_user_stats[user])
                html += '</div>'
            
            # 添加对比选项卡
            html += '<div id="comparison" class="tab-content">'
            html += self._generate_comparison_tab(per_user_stats, user_list, stats)
            html += '</div>'
            
            # 添加选项卡JavaScript
            html += '''
            <script>
            function switchTab(tabId) {
                document.querySelectorAll('.tab-content').forEach(tab => {
                    tab.classList.remove('active');
                });
                document.querySelectorAll('.tab-button').forEach(btn => {
                    btn.classList.remove('active');
                });
                document.getElementById(tabId).classList.add('active');
                event.target.classList.add('active');
            }
            </script>
            '''
        
        # Footer
        footer_html = f"""
        </div>
        
        <!-- Footer -->
        <div class="footer">
            <p>生成时间: {self.timestamp.strftime('%Y年%m月%d日 %H:%M:%S')}</p>
            <p>Git 代码行数统计工具 v1.0 | Powered by Python & Chart.js</p>
        </div>
    </div>"""
        
        html += footer_html
        
        html += f"""
    
    <script>
        // 代码类型分布饼图
        const typeCtx = document.getElementById('typeChart').getContext('2d');
        new Chart(typeCtx, {{
            type: 'doughnut',
            data: {{
                labels: ['前端代码', '后端代码', '其他文件'],
                datasets: [{{
                    data: [{frontend_percent:.2f}, {backend_percent:.2f}, {other_percent:.2f}],
                    backgroundColor: [
                        'rgba(240, 147, 251, 0.8)',
                        'rgba(79, 172, 254, 0.8)',
                        'rgba(67, 233, 123, 0.8)'
                    ],
                    borderColor: [
                        'rgba(240, 147, 251, 1)',
                        'rgba(79, 172, 254, 1)',
                        'rgba(67, 233, 123, 1)'
                    ],
                    borderWidth: 2
                }}]
            }},
            options: {{
                responsive: true,
                maintainAspectRatio: false,
                plugins: {{
                    legend: {{
                        position: 'bottom',
                        labels: {{
                            padding: 20,
                            font: {{
                                size: 12
                            }}
                        }}
                    }},
                    tooltip: {{
                        callbacks: {{
                            label: function(context) {{
                                return context.label + ': ' + context.parsed.toFixed(1) + '%';
                            }}
                        }}
                    }}
                }}
            }}
        }});
        
        // 新增 vs 删除柱状图
        const addDeleteCtx = document.getElementById('addDeleteChart').getContext('2d');
        new Chart(addDeleteCtx, {{
            type: 'bar',
            data: {{
                labels: ['前端', '后端', '其他'],
                datasets: [
                    {{
                        label: '新增',
                        data: [{frontend['added']}, {backend['added']}, {other['added']}],
                        backgroundColor: 'rgba(67, 233, 123, 0.8)',
                        borderColor: 'rgba(67, 233, 123, 1)',
                        borderWidth: 2
                    }},
                    {{
                        label: '删除',
                        data: [{frontend['deleted']}, {backend['deleted']}, {other['deleted']}],
                        backgroundColor: 'rgba(245, 87, 108, 0.8)',
                        borderColor: 'rgba(245, 87, 108, 1)',
                        borderWidth: 2
                    }}
                ]
            }},
            options: {{
                responsive: true,
                maintainAspectRatio: false,
                plugins: {{
                    legend: {{
                        position: 'bottom',
                        labels: {{
                            padding: 15,
                            font: {{
                                size: 12
                            }}
                        }}
                    }}
                }},
                scales: {{
                    y: {{
                        beginAtZero: true,
                        ticks: {{
                            callback: function(value) {{
                                return value.toLocaleString();
                            }}
                        }}
                    }}
                }}
            }}
        }});
        
        // 前端 vs 后端对比
        const comparisonCtx = document.getElementById('comparisonChart').getContext('2d');
        new Chart(comparisonCtx, {{
            type: 'bar',
            data: {{
                labels: ['新增行数', '删除行数', '净增行数'],
                datasets: [
                    {{
                        label: '前端',
                        data: [{frontend['added']}, {frontend['deleted']}, {frontend['total']}],
                        backgroundColor: 'rgba(240, 147, 251, 0.8)',
                        borderColor: 'rgba(240, 147, 251, 1)',
                        borderWidth: 2
                    }},
                    {{
                        label: '后端',
                        data: [{backend['added']}, {backend['deleted']}, {backend['total']}],
                        backgroundColor: 'rgba(79, 172, 254, 0.8)',
                        borderColor: 'rgba(79, 172, 254, 1)',
                        borderWidth: 2
                    }}
                ]
            }},
            options: {{
                responsive: true,
                maintainAspectRatio: false,
                plugins: {{
                    legend: {{
                        position: 'bottom',
                        labels: {{
                            padding: 15,
                            font: {{
                                size: 12
                            }}
                        }}
                    }}
                }},
                scales: {{
                    y: {{
                        beginAtZero: true,
                        ticks: {{
                            callback: function(value) {{
                                return value.toLocaleString();
                            }}
                        }}
                    }}
                }}
            }}
        }});
        
        // 初始化 DataTable
        $(document).ready(function() {{
            $('#filesTable').DataTable({{
                "pageLength": 25,
                "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "全部"]],
                "language": {{
                    "lengthMenu": "每页显示 _MENU_ 条记录",
                    "zeroRecords": "没有找到匹配的记录",
                    "info": "显示第 _START_ 到 _END_ 条记录，共 _TOTAL_ 条",
                    "infoEmpty": "没有可用记录",
                    "infoFiltered": "(从 _MAX_ 条记录中过滤)",
                    "search": "搜索:",
                    "paginate": {{
                        "first": "首页",
                        "last": "末页",
                        "next": "下一页",
                        "previous": "上一页"
                    }}
                }},
                "order": [[4, "desc"]],  // 默认按净增行数降序排序
                "columnDefs": [
                    {{ "orderable": true, "targets": "_all" }},
                    {{ "className": "rank-cell", "targets": 0 }},
                    {{ "className": "file-path-cell", "targets": 1 }},
                    {{ "className": "number-cell", "targets": [2, 3, 4, 5] }}
                ]
            }});
        }});
    </script>
</body>
</html>"""
        
        return html
    
    def _generate_file_list(self, sorted_files) -> str:
        """生成文件列表 HTML"""
        html = ""
        
        for i, (file_path, stats) in enumerate(sorted_files, 1):
            net_change = stats['added'] - stats['deleted']
            
            # 根据排名设置图标
            medal = ""
            if i == 1:
                medal = "🥇"
            elif i == 2:
                medal = "🥈"
            elif i == 3:
                medal = "🥉"
            
            html += f"""
                    <div class="file-item">
                        <div class="file-rank">{medal if medal else i}</div>
                        <div class="file-info">
                            <div class="file-path">{file_path}</div>
                            <div class="file-stats">
                                <span class="stat-badge added">+{stats['added']:,} 新增</span>
                                <span class="stat-badge deleted">-{stats['deleted']:,} 删除</span>
                                <span class="stat-badge net">净增 {net_change:,}</span>
                            </div>
                        </div>
                    </div>"""
        
        return html
    
    def _generate_full_file_table(self, file_stats) -> str:
        """生成完整文件统计表格"""
        import os
        
        # 排序所有文件，但过滤掉没有贡献的文件
        sorted_files = sorted(
            [(f, s) for f, s in file_stats.items() if s['added'] > 0 or s['deleted'] > 0],
            key=lambda x: x[1]['added'] - x[1]['deleted'],
            reverse=True
        )
        
        # 开始表格
        html = """
                    <table id="filesTable" class="display" style="width:100%">
                        <thead>
                            <tr>
                                <th>排名</th>
                                <th>文件路径</th>
                                <th>新增行数</th>
                                <th>删除行数</th>
                                <th>净增行数</th>
                                <th>变更总数</th>
                            </tr>
                        </thead>
                        <tbody>"""
        
        # 数据行
        for idx, (file_path, stats) in enumerate(sorted_files, 1):
            net_change = stats['added'] - stats['deleted']
            total_change = stats['added'] + stats['deleted']
            
            # 获取文件扩展名
            _, ext = os.path.splitext(file_path.lower())
            
            # 判断文件类型
            frontend_exts = {'.html', '.htm', '.css', '.scss', '.sass', '.less',
                           '.js', '.jsx', '.ts', '.tsx', '.vue', '.svelte'}
            backend_exts = {'.py', '.java', '.go', '.rb', '.php', '.c', '.cpp',
                          '.cs', '.rs', '.kt', '.scala', '.swift', '.sql'}
            
            ext_class = ""
            if ext in frontend_exts:
                ext_class = "frontend"
            elif ext in backend_exts:
                ext_class = "backend"
            
            # 排名样式
            rank_class = ""
            rank_display = str(idx)
            if idx == 1:
                rank_class = "rank-1"
                rank_display = "🥇"
            elif idx == 2:
                rank_class = "rank-2"
                rank_display = "🥈"
            elif idx == 3:
                rank_class = "rank-3"
                rank_display = "🥉"
            
            # 净增数字颜色
            net_class = ""
            if net_change > 0:
                net_class = "positive-number"
            elif net_change < 0:
                net_class = "negative-number"
            
            # 添加扩展名标签（如果有）
            file_display = file_path
            if ext:
                ext_badge = f'<span class="extension-badge {ext_class}">{ext}</span> '
                # 在文件名前添加标签
                file_display = f"{ext_badge}{file_path}"
            
            html += f"""
                            <tr>
                                <td class="{rank_class}">{rank_display}</td>
                                <td>{file_display}</td>
                                <td>{stats['added']:,}</td>
                                <td>{stats['deleted']:,}</td>
                                <td class="{net_class}">{net_change:+,}</td>
                                <td>{total_change:,}</td>
                            </tr>"""
        
        html += """
                        </tbody>
                    </table>"""
        
        return html
    
    def _generate_user_tab_content(self, user: str, user_data: Dict) -> str:
        """生成单个账户的选项卡内容"""
        user_stats = user_data['stats']
        user_file_stats = user_data['file_stats']
        
        frontend = user_stats['frontend']
        backend = user_stats['backend']
        other = user_stats['other']
        
        total_added = frontend['added'] + backend['added'] + other['added']
        total_deleted = frontend['deleted'] + backend['deleted'] + other['deleted']
        total_net = frontend['total'] + backend['total'] + other['total']
        total_current = frontend.get('current', 0) + backend.get('current', 0) + other.get('current', 0)
        work_ratio = (total_added / total_current * 100) if total_current > 0 else 0
        
        html = f'''
        <div class="section">
            <h2 class="section-title">👤 账户: {user}</h2>
            
            <!-- 概览卡片 -->
            <div class="summary-cards">
                <div class="summary-card">
                    <div class="label">累计新增</div>
                    <div class="number">{total_added:,}</div>
                </div>
                <div class="summary-card">
                    <div class="label">累计删除</div>
                    <div class="number">{total_deleted:,}</div>
                </div>
                <div class="summary-card">
                    <div class="label">净增行数</div>
                    <div class="number">{total_net:,}</div>
                </div>
                <div class="summary-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                    <div class="label">当前代码量</div>
                    <div class="number">{total_current:,}</div>
                </div>
                <div class="summary-card" style="background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);">
                    <div class="label">工作效率比</div>
                    <div class="number" style="font-size: 32px;">{work_ratio:.0f}%</div>
                    <div style="font-size: 12px; margin-top: 5px;">累计÷当前</div>
                </div>
            </div>
        </div>
        
        <!-- 分类统计 -->
        <div class="section">
            <h2 class="section-title">📂 分类统计</h2>
            <div class="stats-grid">
                <div class="stat-card">
                    <h3>🎨 前端代码</h3>
                    <div class="stat-row">
                        <span class="stat-label">累计新增:</span>
                        <span class="stat-value">{frontend['added']:,}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">累计删除:</span>
                        <span class="stat-value">{frontend['deleted']:,}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">净增:</span>
                        <span class="stat-value">{frontend['total']:,}</span>
                    </div>
                    <div class="stat-row" style="border-top: 2px solid rgba(255,255,255,0.3); padding-top: 10px; margin-top: 10px;">
                        <span class="stat-label">当前拥有:</span>
                        <span class="stat-value" style="font-size: 1.3em; font-weight: bold;">{frontend['current']:,}</span>
                    </div>
                </div>
                
                <div class="stat-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                    <h3>⚙️ 后端代码</h3>
                    <div class="stat-row">
                        <span class="stat-label">累计新增:</span>
                        <span class="stat-value">{backend['added']:,}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">累计删除:</span>
                        <span class="stat-value">{backend['deleted']:,}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">净增:</span>
                        <span class="stat-value">{backend['total']:,}</span>
                    </div>
                    <div class="stat-row" style="border-top: 2px solid rgba(255,255,255,0.3); padding-top: 10px; margin-top: 10px;">
                        <span class="stat-label">当前拥有:</span>
                        <span class="stat-value" style="font-size: 1.3em; font-weight: bold;">{backend['current']:,}</span>
                    </div>
                </div>
                
                <div class="stat-card" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
                    <h3>📄 其他代码</h3>
                    <div class="stat-row">
                        <span class="stat-label">累计新增:</span>
                        <span class="stat-value">{other['added']:,}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">累计删除:</span>
                        <span class="stat-value">{other['deleted']:,}</span>
                    </div>
                    <div class="stat-row">
                        <span class="stat-label">净增:</span>
                        <span class="stat-value">{other['total']:,}</span>
                    </div>
                    <div class="stat-row" style="border-top: 2px solid rgba(255,255,255,0.3); padding-top: 10px; margin-top: 10px;">
                        <span class="stat-label">当前拥有:</span>
                        <span class="stat-value" style="font-size: 1.3em; font-weight: bold;">{other['current']:,}</span>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 修改文件 -->
        <div class="section">
            <h2 class="section-title">📁 修改文件 ({len(user_file_stats)} 个)</h2>
            <div class="full-file-list">
                <p style="color: #6c757d; margin-bottom: 15px;">
                    💡 提示：可以使用搜索框查找文件，点击列标题排序，每页显示数量可调整
                </p>
                <table id="files-table-{user.replace('<', '').replace('>', '').replace('@', '-')}" class="display" style="width:100%">
                    <thead>
                        <tr>
                            <th>排名</th>
                            <th>文件路径</th>
                            <th>新增</th>
                            <th>删除</th>
                            <th>净增</th>
                            <th>当前拥有</th>
                        </tr>
                    </thead>
                    <tbody>
        '''
        
        # 显示所有文件，但过滤掉没有贡献的文件
        sorted_files = sorted(
            [(f, s) for f, s in user_file_stats.items() if s['added'] > 0 or s['deleted'] > 0 or s.get('current', 0) > 0],
            key=lambda x: x[1]['added'] - x[1]['deleted'],
            reverse=True
        )
        for idx, (file_path, file_stat) in enumerate(sorted_files, 1):
            net_change = file_stat['added'] - file_stat['deleted']
            current = file_stat.get('current', 0)
            html += f'''
                        <tr>
                            <td>{idx}</td>
                            <td style="font-family: monospace; font-size: 0.9em;">{file_path}</td>
                            <td>{file_stat['added']:,}</td>
                            <td>{file_stat['deleted']:,}</td>
                            <td>{net_change:,}</td>
                            <td style="font-weight: bold; color: #f5576c;">{current:,}</td>
                        </tr>
            '''
        
        html += '''
                    </tbody>
                </table>
            </div>
        </div>
        
        <script>
        $(document).ready(function() {{
            $('#files-table-{user_id}').DataTable({{
                "pageLength": 25,
                "lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "全部"]],
                "language": {{
                    "lengthMenu": "每页显示 _MENU_ 条记录",
                    "zeroRecords": "没有找到匹配的记录",
                    "info": "显示第 _START_ 到 _END_ 条记录，共 _TOTAL_ 条",
                    "infoEmpty": "没有可用记录",
                    "infoFiltered": "(从 _MAX_ 条记录中过滤)",
                    "search": "搜索:",
                    "paginate": {{
                        "first": "首页",
                        "last": "末页",
                        "next": "下一页",
                        "previous": "上一页"
                    }}
                }},
                "order": [[4, "desc"]]
            }});
        }});
        </script>
        '''.replace('{user_id}', user.replace('<', '').replace('>', '').replace('@', '-'))
        
        return html
    
    def _generate_comparison_tab(self, per_user_stats: Dict, user_list: list, total_stats: Dict) -> str:
        """生成对比选项卡"""
        # 计算总当前代码量
        total_current = sum(
            per_user_stats[user]['stats']['frontend']['current'] + 
            per_user_stats[user]['stats']['backend']['current'] + 
            per_user_stats[user]['stats']['other']['current']
            for user in user_list if user in per_user_stats
        )
        
        html = '''
        <div class="section">
            <h2 class="section-title">📈 账户对比分析</h2>
            
            <!-- 对比表格 -->
            <div class="table-container">
                <table class="display" style="width:100%">
                    <thead>
                        <tr>
                            <th style="text-align: left;">账户</th>
                            <th style="text-align: left;">累计新增</th>
                            <th style="text-align: left;">累计删除</th>
                            <th style="text-align: left;">当前代码量</th>
                            <th style="text-align: left;">工作效率比</th>
                            <th style="text-align: left;">贡献占比</th>
                        </tr>
                    </thead>
                    <tbody>
        '''
        
        for user in user_list:
            if user not in per_user_stats:
                continue
            
            user_stats = per_user_stats[user]['stats']
            user_added = user_stats['frontend']['added'] + user_stats['backend']['added'] + user_stats['other']['added']
            user_deleted = user_stats['frontend']['deleted'] + user_stats['backend']['deleted'] + user_stats['other']['deleted']
            user_current = user_stats['frontend']['current'] + user_stats['backend']['current'] + user_stats['other']['current']
            user_ratio = (user_added / user_current * 100) if user_current > 0 else 0
            user_percent = (user_current / total_current * 100) if total_current > 0 else 0
            
            html += f'''
                        <tr>
                            <td style="font-weight: bold;">{user}</td>
                            <td>{user_added:,}</td>
                            <td>{user_deleted:,}</td>
                            <td style="font-weight: bold; color: #f5576c;">{user_current:,}</td>
                            <td>{user_ratio:.0f}%</td>
                            <td style="font-weight: bold; color: #667eea;">{user_percent:.1f}%</td>
                        </tr>
            '''
        
        html += '''
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- 可视化图表 -->
        <div class="section">
            <h2 class="section-title">📊 贡献占比图表</h2>
            <div style="max-width: 600px; margin: 0 auto; background: white; padding: 30px; border-radius: 15px; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);">
                <canvas id="contributionChart"></canvas>
            </div>
        </div>
        
        <script>
        (function() {
            const ctx = document.getElementById('contributionChart');
            if (!ctx) return;
            
            const data = {
        '''
        
        # 生成图表数据
        labels = []
        data_values = []
        colors = ['#667eea', '#f5576c', '#4ecdc4', '#ffa07a', '#98d8c8', '#6c5ce7', '#fdcb6e', '#e17055']
        
        for user in user_list:
            if user not in per_user_stats:
                continue
            labels.append(user)
            user_stats = per_user_stats[user]['stats']
            user_current = user_stats['frontend']['current'] + user_stats['backend']['current'] + user_stats['other']['current']
            data_values.append(user_current)
        
        html += f'''
                labels: {labels},
                datasets: [{{
                    data: {data_values},
                    backgroundColor: {colors[:len(labels)]},
                    borderWidth: 0
                }}]
            }};
            
            new Chart(ctx, {{
                type: 'doughnut',
                data: data,
                options: {{
                    responsive: true,
                    plugins: {{
                        legend: {{
                            position: 'bottom',
                            labels: {{
                                padding: 20,
                                font: {{
                                    size: 14
                                }}
                            }}
                        }},
                        tooltip: {{
                            callbacks: {{
                                label: function(context) {{
                                    const label = context.label || '';
                                    const value = context.parsed || 0;
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = ((value / total) * 100).toFixed(1);
                                    return label + ': ' + value.toLocaleString() + ' 行 (' + percentage + '%)';
                                }}
                            }}
                        }}
                    }}
                }}
            }});
        }})();
        </script>
        '''
        
        return html

